<template>
  <div class="post-detail-container">
    <div class="back-button">
      <el-button @click="goBack" :icon="ArrowLeft">返回</el-button>
    </div>

    <div v-loading="loading" class="content-wrapper">
      <el-card v-if="post" class="post-card">
        <!-- 帖子头部 -->
        <div class="post-header">
          <div class="author-info">
            <el-avatar :size="50">
              {{ (post.nickName || post.username || '用户').charAt(0) }}
            </el-avatar>
            <div class="author-details">
              <div class="author-name">{{ post.nickName || post.username || '匿名用户' }}</div>
              <div class="post-meta">
                <span>{{ formatTime(post.createTime) }}</span>
                <el-divider direction="vertical" />
                <el-tag :type="getCategoryType(post.category)" size="small">
                  {{ getCategoryName(post.category) }}
                </el-tag>
              </div>
            </div>
          </div>

          <el-dropdown v-if="isOwner" trigger="click">
            <el-button circle :icon="MoreFilled" />
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item :icon="Edit" @click="handleEdit">编辑</el-dropdown-item>
                <el-dropdown-item :icon="Delete" @click="handleDelete">删除</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>

        <!-- 帖子标题 -->
        <h1 class="post-title">{{ post.title }}</h1>

        <!-- 帖子内容 -->
        <div class="post-content">
          <div class="content-text">{{ post.content }}</div>

          <!-- 图片展示 -->
          <div v-if="getImageList(post.images).length > 0" class="post-images">
            <el-image
              v-for="(img, index) in getImageList(post.images)"
              :key="index"
              :src="img"
              :preview-src-list="getImageList(post.images)"
              fit="cover"
              class="post-image"
              :preview-teleported="true"
            />
          </div>
        </div>

        <!-- 统计信息 -->
        <div class="post-stats">
          <div class="stat-item">
            <el-icon><View /></el-icon>
            <span>{{ post.viewCount || 0 }} 浏览</span>
          </div>
          <div class="stat-item">
            <el-icon><ChatDotRound /></el-icon>
            <span>{{ post.commentCount || 0 }} 评论</span>
          </div>
          <div class="stat-item">
            <el-icon><Star /></el-icon>
            <span>{{ post.likeCount || 0 }} 点赞</span>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="post-actions">
          <el-button
            :type="post.isLiked ? 'warning' : 'default'"
            size="large"
            @click="toggleLike"
            :loading="liking"
          >
            <el-icon><component :is="post.isLiked ? StarFilled : Star" /></el-icon>
            {{ post.isLiked ? '已点赞' : '点赞' }} ({{ post.likeCount || 0 }})
          </el-button>
        </div>
      </el-card>

      <!-- 评论区 -->
      <el-card class="comments-card">
        <template #header>
          <div class="comments-header">
            <h3>全部评论 ({{ commentTotal }})</h3>
          </div>
        </template>

        <!-- 发表评论 -->
        <div v-if="isLoggedIn" class="comment-input-section">
          <el-input
            v-model="newComment"
            type="textarea"
            :rows="3"
            placeholder="写下你的评论..."
            maxlength="1000"
            show-word-limit
          />
          <div class="comment-actions">
            <el-button type="primary" @click="submitComment" :loading="submitting">
              发表评论
            </el-button>
          </div>
        </div>
        <div v-else class="login-prompt">
          <el-button type="primary" @click="goToLogin">登录后发表评论</el-button>
        </div>

        <!-- 评论列表 -->
        <div v-loading="commentsLoading" class="comments-list">
          <div v-if="comments.length === 0" class="empty-comments">
            <el-empty description="暂无评论，快来发表第一条评论吧！" />
          </div>

          <div v-for="comment in comments" :key="comment.id" class="comment-item">
            <el-avatar :size="36">
              {{ (comment.nickName || comment.username || '用户').charAt(0) }}
            </el-avatar>

            <div class="comment-content">
              <div class="comment-header">
                <span class="comment-author">{{ comment.nickName || comment.username || '匿名用户' }}</span>
                <span class="comment-time">{{ formatTime(comment.createTime) }}</span>
              </div>

              <div class="comment-text">{{ comment.content }}</div>

              <div class="comment-footer">
                <el-button
                  size="small"
                  text
                  :type="comment.isLiked ? 'warning' : 'default'"
                  @click="toggleCommentLike(comment)"
                  :loading="comment.liking"
                >
                  <el-icon><component :is="comment.isLiked ? StarFilled : Star" /></el-icon>
                  {{ comment.likeCount || 0 }}
                </el-button>

                <el-button
                  v-if="isCommentOwner(comment)"
                  size="small"
                  text
                  type="danger"
                  @click="deleteComment(comment)"
                >
                  <el-icon><Delete /></el-icon>
                  删除
                </el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 评论分页 -->
        <div v-if="commentTotalPages > 1" class="comment-pagination">
          <el-pagination
            v-model:current-page="commentPage"
            :page-size="commentPageSize"
            :total="commentTotal"
            layout="prev, pager, next"
            @current-change="loadComments"
          />
        </div>
      </el-card>
    </div>

    <!-- 编辑帖子对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑帖子"
      width="700px"
      :close-on-click-modal="false"
    >
      <el-form :model="editForm" ref="editFormRef" label-width="80px">
        <el-form-item label="标题" prop="title" :rules="[
          { required: true, message: '请输入帖子标题', trigger: 'blur' },
          { min: 1, max: 255, message: '标题长度在1-255个字符', trigger: 'blur' }
        ]">
          <el-input
            v-model="editForm.title"
            placeholder="请输入帖子标题"
            maxlength="255"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="分类" prop="category" :rules="[
          { required: true, message: '请选择分类', trigger: 'change' }
        ]">
          <el-select v-model="editForm.category" placeholder="请选择分类">
            <el-option label="钓鱼经验" value="fishing" />
            <el-option label="求助问答" value="help" />
            <el-option label="技巧分享" value="tips" />
            <el-option label="综合讨论" value="general" />
          </el-select>
        </el-form-item>

        <el-form-item label="内容" prop="content" :rules="[
          { required: true, message: '请输入帖子内容', trigger: 'blur' }
        ]">
          <el-input
            v-model="editForm.content"
            type="textarea"
            :rows="6"
            placeholder="分享你的钓鱼经验..."
            maxlength="5000"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="图片">
          <el-upload
            v-model:file-list="editFileList"
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :on-change="handleEditFileChange"
            :on-remove="handleEditFileRemove"
            accept="image/*"
            multiple
            :limit="9"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">最多上传9张图片，支持jpg、png格式</div>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit" :loading="publishing">
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { postAPI, commentAPI, productAPI } from '@/api'
import {
  ArrowLeft,
  View,
  ChatDotRound,
  Star,
  StarFilled,
  MoreFilled,
  Edit,
  Delete,
  Plus
} from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()

// 响应式数据
const loading = ref(false)
const liking = ref(false)
const submitting = ref(false)
const publishing = ref(false)
const commentsLoading = ref(false)
const post = ref(null)
const comments = ref([])
const newComment = ref('')
const commentPage = ref(1)
const commentPageSize = ref(10)
const commentTotal = ref(0)

// 计算属性
const isLoggedIn = computed(() => !!localStorage.getItem('token'))
const currentUserId = computed(() => {
  try {
    const userInfo = localStorage.getItem('userInfo')
    return userInfo ? JSON.parse(userInfo).userId : null
  } catch {
    return null
  }
})
const isOwner = computed(() => {
  return post.value && currentUserId.value && post.value.userId === currentUserId.value
})
const commentTotalPages = computed(() => Math.ceil(commentTotal.value / commentPageSize.value))

// 获取当前用户ID
const getCurrentUserId = () => {
  try {
    const userInfoStr = localStorage.getItem('userInfo')
    if (userInfoStr) {
      const info = JSON.parse(userInfoStr)
      if (info && (info.userId || info.user_id)) {
        return info.userId || info.user_id
      }
    }
  } catch {}
  
  // 从JWT token中获取用户ID作为备用
  try {
    const token = localStorage.getItem('token') || localStorage.getItem('authToken')
    if (token && token.includes('.')) {
      const payload = JSON.parse(atob(token.split('.')[1] || ''))
      if (payload && (payload.userId || payload.user_id || payload.uid || payload.id)) {
        return payload.userId || payload.user_id || payload.uid || payload.id
      }
    }
  } catch {}
  
  return null
}

// 用户点赞状态管理（按用户ID分组）
const getLikedPosts = () => {
  try {
    const userId = getCurrentUserId()
    if (!userId) return []
    
    const likedPostsData = localStorage.getItem('likedPosts')
    if (!likedPostsData) return []
    
    const allLikedPosts = JSON.parse(likedPostsData)
    
    // 检查是否是旧格式（直接存储数组）
    if (Array.isArray(allLikedPosts)) {
      console.warn('检测到旧格式点赞数据，正在迁移...')
      // 迁移旧数据到新格式
      const newFormat = {}
      newFormat[userId] = allLikedPosts
      localStorage.setItem('likedPosts', JSON.stringify(newFormat))
      return allLikedPosts
    }
    
    // 新格式：按用户ID分组
    const userLikedPosts = allLikedPosts[userId]
    
    // 确保返回的是数组
    if (Array.isArray(userLikedPosts)) {
      return userLikedPosts
    } else {
      console.warn('用户点赞数据不是数组:', userLikedPosts)
      return []
    }
  } catch (error) {
    console.error('获取点赞状态失败:', error)
    return []
  }
}

const saveLikedPost = (postId, liked) => {
  try {
    const userId = getCurrentUserId()
    if (!userId) return
    
    const likedPosts = getLikedPosts()
    if (liked) {
      if (!likedPosts.includes(postId)) {
        likedPosts.push(postId)
      }
    } else {
      const index = likedPosts.indexOf(postId)
      if (index > -1) {
        likedPosts.splice(index, 1)
      }
    }
    
    // 保存到按用户ID分组的数据中
    const likedPostsData = localStorage.getItem('likedPosts')
    const allLikedPosts = likedPostsData ? JSON.parse(likedPostsData) : {}
    allLikedPosts[userId] = likedPosts
    localStorage.setItem('likedPosts', JSON.stringify(allLikedPosts))
  } catch {}
}

const getLikedComments = () => {
  try {
    const userId = getCurrentUserId()
    if (!userId) return []
    
    const likedCommentsData = localStorage.getItem('likedComments')
    if (!likedCommentsData) return []
    
    const allLikedComments = JSON.parse(likedCommentsData)
    
    // 检查是否是旧格式（直接存储数组）
    if (Array.isArray(allLikedComments)) {
      console.warn('检测到旧格式评论点赞数据，正在迁移...')
      // 迁移旧数据到新格式
      const newFormat = {}
      newFormat[userId] = allLikedComments
      localStorage.setItem('likedComments', JSON.stringify(newFormat))
      return allLikedComments
    }
    
    // 新格式：按用户ID分组
    const userLikedComments = allLikedComments[userId]
    
    // 确保返回的是数组
    if (Array.isArray(userLikedComments)) {
      return userLikedComments
    } else {
      console.warn('用户评论点赞数据不是数组:', userLikedComments)
      return []
    }
  } catch (error) {
    console.error('获取评论点赞状态失败:', error)
    return []
  }
}

const saveLikedComment = (commentId, liked) => {
  try {
    const userId = getCurrentUserId()
    if (!userId) return
    
    const likedComments = getLikedComments()
    if (liked) {
      if (!likedComments.includes(commentId)) {
        likedComments.push(commentId)
      }
    } else {
      const index = likedComments.indexOf(commentId)
      if (index > -1) {
        likedComments.splice(index, 1)
      }
    }
    
    // 保存到按用户ID分组的数据中
    const likedCommentsData = localStorage.getItem('likedComments')
    const allLikedComments = likedCommentsData ? JSON.parse(likedCommentsData) : {}
    allLikedComments[userId] = likedComments
    localStorage.setItem('likedComments', JSON.stringify(allLikedComments))
  } catch {}
}

// 图片处理 - 参考商城的 parseCoverList 函数
const getImageList = (images) => {
  // 如果为空，返回空数组
  if (!images) return []
  
  // 如果已经是数组，过滤后返回
  if (Array.isArray(images)) {
    // 检查数组第一个元素是否是对象（包含successUrls）
    if (images.length > 0 && images[0] && typeof images[0] === 'object' && images[0].successUrls) {
      return images[0].successUrls.filter(img => img && typeof img === 'string' && !img.startsWith('blob:'))
    }
    return images.filter(img => img && typeof img === 'string' && !img.startsWith('blob:'))
  }
  
  // 如果是字符串，尝试解析
  if (typeof images === 'string') {
    // 如果是空字符串，返回空数组
    if (!images.trim()) {
      return []
    }
    
    // 如果看起来像单个URL（以http开头），包装成数组
    if (images.startsWith('http')) {
      return [images]
    }
    
    // 尝试解析JSON字符串
    try {
      const parsed = JSON.parse(images)
      
      // 如果解析结果是数组
      if (Array.isArray(parsed)) {
        // 检查是否是 [{successUrls: [...]}] 格式
        if (parsed.length > 0 && parsed[0] && typeof parsed[0] === 'object' && parsed[0].successUrls) {
          return parsed[0].successUrls.filter(img => img && typeof img === 'string' && !img.startsWith('blob:'))
        }
        // 普通URL数组
        return parsed.filter(img => img && typeof img === 'string' && !img.startsWith('blob:'))
      }
      
      // 如果解析结果是对象且包含successUrls
      if (parsed && typeof parsed === 'object' && parsed.successUrls && Array.isArray(parsed.successUrls)) {
        return parsed.successUrls.filter(img => img && typeof img === 'string' && !img.startsWith('blob:'))
      }
      
      // 如果解析结果是单个URL字符串
      if (typeof parsed === 'string' && parsed) {
        return [parsed]
      }
      
      return []
    } catch (error) {
      console.warn('解析图片列表失败:', images)
      return []
    }
  }
  
  // 其他情况返回空数组
  return []
}

// 获取帖子详情
const fetchPostDetail = async () => {
  try {
    loading.value = true
    const postId = route.params.id
    const response = await postAPI.getPostDetail(postId)
    
    if (response.code === 0) {
      post.value = {
        ...response.data,
        isLiked: getLikedPosts().includes(response.data.id)
      }
      
      // 增加浏览次数
      postAPI.viewPost(postId).catch(() => {})
    } else {
      ElMessage.error(response.message || '获取帖子详情失败')
      goBack()
    }
  } catch (error) {
    ElMessage.error('获取帖子详情失败')
    goBack()
  } finally {
    loading.value = false
  }
}

// 加载评论
const loadComments = async (page = 1) => {
  try {
    commentsLoading.value = true
    const postId = route.params.id
    const response = await commentAPI.getCommentsByPost(postId, {
      page: page,
      size: commentPageSize.value
    })
    
    if (response.code === 0) {
      const likedComments = getLikedComments()
      comments.value = (response.data.comments || []).map(comment => ({
        ...comment,
        isLiked: likedComments.includes(comment.id),
        liking: false
      }))
      commentTotal.value = response.data.total || 0
      commentPage.value = page
    }
  } catch (error) {
    ElMessage.error('获取评论失败')
  } finally {
    commentsLoading.value = false
  }
}

// 点赞帖子
const toggleLike = async () => {
  if (!isLoggedIn.value) {
    ElMessageBox.confirm(
      '点赞功能需要登录后才能使用，是否前往登录页面？',
      '需要登录',
      {
        confirmButtonText: '去登录',
        cancelButtonText: '取消',
        type: 'info',
        showClose: false
      }
    ).then(() => {
      router.push('/userLogin')
    }).catch(() => {
      // 用户取消，不做任何操作
    })
    return
  }
  
  try {
    liking.value = true
    const response = await postAPI.likePost(post.value.id)
    
    if (response.code === 0) {
      post.value.isLiked = !post.value.isLiked
      
      if (post.value.isLiked) {
        post.value.likeCount = (post.value.likeCount || 0) + 1
        saveLikedPost(post.value.id, true)
        ElMessage.success('点赞成功')
      } else {
        post.value.likeCount = Math.max(0, (post.value.likeCount || 0) - 1)
        saveLikedPost(post.value.id, false)
        ElMessage.success('取消点赞')
      }
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    ElMessage.error('操作失败')
  } finally {
    liking.value = false
  }
}

// 发表评论
const submitComment = async () => {
  if (!newComment.value.trim()) {
    ElMessage.warning('请输入评论内容')
    return
  }
  
  try {
    submitting.value = true
    const response = await commentAPI.createComment({
      postId: post.value.id,
      content: newComment.value
    })
    
    if (response.code === 0) {
      ElMessage.success('评论发表成功')
      newComment.value = ''
      post.value.commentCount = (post.value.commentCount || 0) + 1
      commentPage.value = 1
      await loadComments(1)
    } else {
      ElMessage.error(response.message || '发表评论失败')
    }
  } catch (error) {
    ElMessage.error('发表评论失败')
  } finally {
    submitting.value = false
  }
}

// 点赞评论
const toggleCommentLike = async (comment) => {
  if (!isLoggedIn.value) {
    ElMessageBox.confirm(
      '点赞功能需要登录后才能使用，是否前往登录页面？',
      '需要登录',
      {
        confirmButtonText: '去登录',
        cancelButtonText: '取消',
        type: 'info',
        showClose: false
      }
    ).then(() => {
      router.push('/userLogin')
    }).catch(() => {
      // 用户取消，不做任何操作
    })
    return
  }
  
  if (comment.liking) return
  
  try {
    comment.liking = true
    const response = await commentAPI.likeComment(comment.id)
    
    if (response.code === 0) {
      comment.isLiked = !comment.isLiked
      
      if (comment.isLiked) {
        comment.likeCount = (comment.likeCount || 0) + 1
        saveLikedComment(comment.id, true)
      } else {
        comment.likeCount = Math.max(0, (comment.likeCount || 0) - 1)
        saveLikedComment(comment.id, false)
      }
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    ElMessage.error('操作失败')
  } finally {
    comment.liking = false
  }
}

// 删除评论
const deleteComment = async (comment) => {
  try {
    await ElMessageBox.confirm('确定要删除这条评论吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await commentAPI.deleteComment(comment.id)
    
    if (response.code === 0) {
      ElMessage.success('评论删除成功')
      post.value.commentCount = Math.max(0, (post.value.commentCount || 0) - 1)
      await loadComments(commentPage.value)
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 编辑帖子对话框
const editDialogVisible = ref(false)
const editFormRef = ref()
const editForm = reactive({
  title: '',
  content: '',
  category: 'general',
  images: []
})
const editFileList = ref([])

// 编辑帖子
const handleEdit = () => {
  // 填充表单数据
  editForm.title = post.value.title
  editForm.content = post.value.content
  editForm.category = post.value.category
  
  // 处理已有图片
  const existingImages = getImageList(post.value.images)
  editFileList.value = existingImages.map((url, index) => ({
    uid: -index - 1,
    name: `image-${index}.jpg`,
    status: 'success',
    url: url
  }))
  
  editDialogVisible.value = true
}

// 提交编辑
const submitEdit = async () => {
  try {
    await editFormRef.value.validate()
    
    publishing.value = true
    
    // 处理图片：分离新上传的和已存在的
    const newFiles = editFileList.value.filter(file => file.raw)
    const existingUrls = editFileList.value.filter(file => !file.raw && file.url).map(file => file.url)
    
    // 上传新图片
    let uploadedUrls = []
    if (newFiles.length > 0) {
      const rawFiles = newFiles.map(file => file.raw).filter(f => f)
      if (rawFiles.length > 0) {
        const response = await productAPI.uploadImages(rawFiles)
        if (response.code === 0 && response.data) {
          // 处理后端返回的数据格式
          if (response.data.successUrls && Array.isArray(response.data.successUrls)) {
            uploadedUrls = response.data.successUrls
          } else if (Array.isArray(response.data)) {
            uploadedUrls = response.data
          } else if (typeof response.data === 'string') {
            uploadedUrls = [response.data]
          }
        }
      }
    }
    
    // 合并所有图片URL
    const allImageUrls = [...existingUrls, ...uploadedUrls]
    
    // 提交更新
    const updateData = {
      id: post.value.id,
      title: editForm.title,
      content: editForm.content,
      category: editForm.category,
      images: allImageUrls.length > 0 ? JSON.stringify(allImageUrls) : null
    }
    
    const response = await postAPI.updatePost(updateData)
    
    if (response.code === 0) {
      ElMessage.success('帖子更新成功！')
      editDialogVisible.value = false
      await fetchPostDetail()
    } else {
      ElMessage.error(response.message || '更新失败')
    }
  } catch (error) {
    if (error.message) {
      ElMessage.error(error.message)
    }
  } finally {
    publishing.value = false
  }
}

const handleEditFileChange = (file, files) => {
  editFileList.value = files
}

const handleEditFileRemove = (file, files) => {
  editFileList.value = files
}

// 删除帖子
const handleDelete = async () => {
  try {
    await ElMessageBox.confirm('确定要删除这个帖子吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await postAPI.deletePost(post.value.id)
    
    if (response.code === 0) {
      ElMessage.success('帖子删除成功')
      router.push('/community/CommunityHome')
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 判断是否是评论作者
const isCommentOwner = (comment) => {
  return currentUserId.value && comment.userId === currentUserId.value
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 跳转登录
const goToLogin = () => {
  router.push('/userLogin')
}

// 时间格式化
const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  const now = new Date()
  const diff = now - date
  
  const minute = 60 * 1000
  const hour = 60 * minute
  const day = 24 * hour
  
  if (diff < minute) return '刚刚'
  if (diff < hour) return `${Math.floor(diff / minute)}分钟前`
  if (diff < day) return `${Math.floor(diff / hour)}小时前`
  if (diff < 7 * day) return `${Math.floor(diff / day)}天前`
  
  return date.toLocaleDateString('zh-CN')
}

// 分类信息
const getCategoryName = (category) => {
  const map = {
    fishing: '钓鱼经验',
    help: '求助问答',
    tips: '技巧分享',
    general: '综合讨论'
  }
  return map[category] || '其他'
}

const getCategoryType = (category) => {
  const map = {
    fishing: 'primary',
    help: 'warning',
    tips: 'success',
    general: 'info'
  }
  return map[category] || 'info'
}

// 页面加载
onMounted(() => {
  // 防止因图片预览或弹窗残留，导致页面滚动被锁
  try {
    document.body.classList.remove('el-popup-parent--hidden')
    if (document.body.style.overflow === 'hidden') {
      document.body.style.overflow = ''
    }
  } catch {}

  fetchPostDetail()
  loadComments(1)
})
</script>

<style scoped>
.post-detail-container {
  max-width: 900px;
  margin: 0 auto;
  padding: 24px;
}

.back-button {
  margin-bottom: 20px;
}

.content-wrapper {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.post-card,
.comments-card {
  border-radius: 12px;
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.author-info {
  display: flex;
  gap: 12px;
}

.author-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.author-name {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.post-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #909399;
}

.post-title {
  margin: 0 0 24px 0;
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  line-height: 1.4;
}

.post-content {
  margin-bottom: 24px;
}

.content-text {
  color: #606266;
  line-height: 1.8;
  font-size: 16px;
  white-space: pre-wrap;
  word-break: break-word;
}

.post-images {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 12px;
  margin-top: 20px;
}

.post-image {
  width: 100%;
  height: 200px;
  border-radius: 8px;
  cursor: pointer;
}

.post-stats {
  display: flex;
  gap: 32px;
  padding: 16px 0;
  border-top: 1px solid #ebeef5;
  border-bottom: 1px solid #ebeef5;
  margin-bottom: 20px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #606266;
  font-size: 14px;
}

.post-actions {
  display: flex;
  gap: 12px;
}

.comments-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.comment-input-section {
  margin-bottom: 24px;
}

.comment-actions {
  margin-top: 12px;
  text-align: right;
}

.login-prompt {
  text-align: center;
  padding: 32px 0;
}

.comments-list {
  min-height: 200px;
}

.empty-comments {
  padding: 40px 0;
}

.comment-item {
  display: flex;
  gap: 12px;
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
}

.comment-item:last-child {
  border-bottom: none;
}

.comment-content {
  flex: 1;
}

.comment-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
}

.comment-author {
  font-weight: 600;
  color: #303133;
}

.comment-time {
  font-size: 12px;
  color: #909399;
}

.comment-text {
  color: #606266;
  line-height: 1.6;
  margin-bottom: 8px;
  white-space: pre-wrap;
  word-break: break-word;
}

.comment-footer {
  display: flex;
  gap: 16px;
}

.comment-pagination {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .post-detail-container {
    padding: 12px;
  }

  .post-title {
    font-size: 22px;
  }

  .post-images {
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  }

  .post-image {
    height: 150px;
  }

  .post-stats {
    flex-wrap: wrap;
    gap: 16px;
  }
}

.upload-tip {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
}
</style>
